package com.gt.andr.jsi;


import add.Adder;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

public class MainWebViewActivity extends Activity {
	/** Called when the activity is first created. */
	WebView webView;
	Button callBtn;
	
//	TextView showTv;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.browser);
		initComponents();
		Adder.add(3,3);
	}

	private void initComponents() {
		webView = (WebView) findViewById(R.id.webView);
		WebSettings webSettings = webView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
		webView.loadUrl("file:///android_res/raw/test.html");
		webView.setWebChromeClient(new JsChromeClient());
		callBtn = (Button)findViewById(R.id.callBtn);
		callBtn.setOnClickListener( new OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				webView.loadUrl("javascript:sayHello('Hello From Android to JavaScript')");
				webView.loadUrl("javascript:getValue()");
				
			}
		});
//		showTv = (TextView) findViewById(R.id.retValueTv);
	}

	/**
	 * 
	 * @author ith
	 * 
	 */
	public class JavaScriptInterface {
		Context mContext;

		/** Instantiate the interface and set the context */
		JavaScriptInterface(Context c) {
			mContext = c;
		}

		/** Show a toast from the web page */
		public void showToast(String toast) {
			Toast.makeText(mContext, "Received Msg :" + toast, Toast.LENGTH_SHORT).show();
//			showTv.setText(toast);
		}

		public void showValue(String val) {
			Toast.makeText(mContext, "Received Value :" + val, Toast.LENGTH_SHORT).show();
//			showTv.setText(val);
		}
		public String sendValueToJs(){
			System.out.println("sendValueToJs called");
			return "sent from android";
		}
		public void receiveValueFromJs(String str) {
			Toast.makeText(mContext, "Received Value from JS: " + str, Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 
	 * @author ith
	 * 
	 */
	private class JsChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
			new AlertDialog.Builder(MainWebViewActivity.this).setTitle("JavaScript Alert !").setMessage(message)
					.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							result.confirm();
						}
					}).setCancelable(false).create().show();

			return true;
		}
	}
}